package com.jiazhong.boot.jwt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.boot.commons.bean.plus.User;
import com.jiazhong.boot.commons.config.JwtConfig;
import com.jiazhong.boot.commons.util.JsonResult;
import com.jiazhong.boot.commons.util.MD5Util;
import com.jiazhong.boot.commons.util.ResultTool;
import com.jiazhong.boot.jwt.mapper.UserMapper;
import com.jiazhong.boot.jwt.service.UserService;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult login(User user) {
        // 1. 验证账号是否正确
        User one = checkUsername(user.getUsername());
        if (one == null) {
            return ResultTool.fail(501, "账号不存在");
        }
        // 2. 验证密码是否正确
        if (!one.getPassword().equals(MD5Util.encryptMD5(user.getPassword()))) {
            return ResultTool.fail(502, "密码错误");
        }
        // 3. 根据one生成token令牌
        String token = JwtConfig.getJwtToken(one);
        log.info("token:{}", token);
        // 4. 服务器保存token
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        forValue.set("token:" + one.getId(), token, 1, TimeUnit.DAYS);
        // 5. 返回token
        return ResultTool.success(token);
    }

    @Override
    public JsonResult isLogin(String token) {
        // 用户送过来的token
        // 检查token是否合法
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return ResultTool.fail(501, "用户没有登陆");
        }
        // 获取到user_id
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        // 获取到redis中存放到token
        String redisToken = stringRedisTemplate.opsForValue().get("token:" + userId);
        if (redisToken == null) {
            return ResultTool.fail(501, "用户没有登陆");
        }
        if (!Objects.equals(redisToken, token)) {
            return ResultTool.fail(501, "用户没有登陆");
        }
        return ResultTool.success(claims.get("name"));
    }

    @Override
    public JsonResult logout(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return ResultTool.fail(501, "登出失败");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        Boolean delete = stringRedisTemplate.delete("token:" + userId);
        if (!delete) {
            return ResultTool.fail(501, "登出失败");
        }
        return ResultTool.success("success");
    }

    private User checkUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return getOne(queryWrapper);
    }
}
